/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.simon.mengkou.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;

import com.simon.mengkou.R;

import java.lang.reflect.Field;

/**
 * @author : Zhenshui.Xia
 * @since : 2016/1/7.
 * desc    :描边字体
 */
public class StrokeTextView extends TextView{
    private Paint mPaint;
    //字体颜色
    private int mInlineColor = Color.WHITE;
    //轮廓颜色
    private int mOutlineColor = Color.BLACK;

    public StrokeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = getPaint();
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.StrokeTextView);
        mInlineColor = a.getColor(R.styleable.StrokeTextView_inlineColor, Color.WHITE);
        mOutlineColor = a.getColor(R.styleable.StrokeTextView_outlineColor, Color.BLACK);
        a.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // 描外层
        //super.setTextColor(Color.BLUE); // 不能直接这么设，如此会导致递归
        setTextColorUseReflection(mOutlineColor);
        mPaint.setStrokeWidth(3);  // 描边宽度
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE); //描边种类
        mPaint.setFakeBoldText(true); // 外层text采用粗体
        mPaint.setShadowLayer(1, 0, 0, 0); //字体的阴影效果，可以忽略
        super.onDraw(canvas);


        // 描内层，恢复原先的画笔

        //super.setTextColor(Color.BLUE); // 不能直接这么设，如此会导致递归
        setTextColorUseReflection(mInlineColor);
        mPaint.setStrokeWidth(0);
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        mPaint.setFakeBoldText(false);
        mPaint.setShadowLayer(0, 0, 0, 0);
        
        super.onDraw(canvas);
    }

    /**
     * 设置字体颜色
     * @param inlineColor
     * @param outlineColor
     */
    public void setTextColor(int inlineColor, int outlineColor) {
        mInlineColor = inlineColor;
        mOutlineColor = outlineColor;
    }

    private void setTextColorUseReflection(int color) {
        Field textColorField;
        try {
            textColorField = TextView.class.getDeclaredField("mCurTextColor");
            textColorField.setAccessible(true);
            textColorField.set(this, color);
            textColorField.setAccessible(false);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        mPaint.setColor(color);
    }
}
